package config
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.LoaderMax;
	import com.greensock.loading.XMLLoader;
	
	import flash.utils.Dictionary;
	import flash.utils.getTimer;
	
	import util.Util;

	/**
	 *读取配置文件 
	 * @author SXT
	 */
	public class ConLoader
	{
		/**
		 *等待加载的文件列表 
		 */
		private var configList:Array;
		
		public var configDic:Dictionary;
		/**
		 *载入完执行的方法 
		 */		
		private var fun:Function;
		
		public function ConLoader()
		{
			configDic = new Dictionary();
		}
		public function loadConfig(arr:Array,fun:Function=null):void{
			this.fun = fun;
			this.configList = arr;
			var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});  
			for each(var name:String in arr){
				queue.append( new XMLLoader(Constant.CONFIG_PATH + name + ".txt", {name:name}) ); 
			}
			queue.load(); 
		}
		private function progressHandler(event:LoaderEvent):void {  
			trace("progress: " + event.target.progress); 
		}   
		private function completeHandler(event:LoaderEvent):void { 
			var t1:int = getTimer();
			trace(event.target + " is complete!");
			for each(var name:String in configList){
				var list:Dictionary = new Dictionary();
				var text:String = LoaderMax.getContent(name);  
				var tmpArr:Array = text.split("\r");
				var tmpTitle:Array = String(tmpArr[1]).split("\t");
				for (var i:int = 2;i<tmpArr.length;i++){
					var tmpValue:Array = String(tmpArr[i]).split("\t");
					var obj:Object = new Object();
					for(var j:int = 0;j<tmpValue.length;j++){
						if(j == 0){
							obj[Util.getPurity(tmpTitle[j],"id")] = Util.getPurity(tmpValue[j],"0-9");
						}else{
							obj[tmpTitle[j]] = tmpValue[j];
						}
					}
					list[obj["id"]] = (obj);
				}
				configDic[name] = list;
			}
			trace("初始化配置文件用时：" + (getTimer()-t1)," ,文件个数：" + configList.length);
			if(fun != null){
				fun();
			}
		}  
		private function errorHandler(event:LoaderEvent):void {  
			trace("error occured with " + event.target + ": " + event.text); 
		}
	}
}